package 实验三.二层cs;

import java.io.*;
import java.net.*;
import java.util.*;

public class Server {
    private static List<Contact> contacts = new ArrayList<>();
    private static Map<String, Integer> contactIndex = new HashMap<>();

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;

        try {
            serverSocket = new ServerSocket(12345);
            System.out.println("服务器启动，等待客户端连接...");

            socket = serverSocket.accept();
            System.out.println("客户端已连接");

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            String inputLine;
            String response="";//给客户端的响应
            while ((inputLine = in.readLine()) != null) {
                String[] parts = inputLine.split("-");
                String action = parts[0];

                switch (action) {
                    case "1":
                        addContact(new Contact(parts[1], parts[2], parts[3]));
                        //给客户端返回响应
                        response="添加成功";
                        break;
                    case "2":
                        response= modifyContact(parts[1], parts[2], parts[3]);
                        System.out.println("respone "+response);
                        break;
                    case "3":
                        deleteContact(parts[1]);
                        response="删除成功";
                        break;
                    case "4":
                        out.println(viewContact());
                        response="查询成功";
                        break;
                    default:
                        System.out.println("未知操作：" + inputLine);
                        break;
                }
                out.println(response);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (socket != null) socket.close();
                if (serverSocket != null) serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void addContact(Contact contact) {
        if (contactIndex.containsKey(contact.name)) {
            System.out.println("该联系人已存在（服务器）");
        } else {
            contacts.add(contact);
            contactIndex.put(contact.name, contacts.size() - 1);
            System.out.println("联系人添加成功（服务器）");
        }
    }

    private static String modifyContact(String name, String address, String phone) {
        if (contactIndex.containsKey(name)) {
            contacts.get(contactIndex.get(name)).address = address;
            contacts.get(contactIndex.get(name)).phone = phone;
            System.out.println("联系人修改成功（服务器）");
            return contacts.get(contactIndex.get(name)).toString();
        } else {
            System.out.println("联系人不存在（服务器）");
        }
        return "联系人不存在（服务器）";
    }

    private static void deleteContact(String name) {
        if (contactIndex.containsKey(name)) {
            contacts.remove(contactIndex.get(name));
            contactIndex.remove(name);
            System.out.println("联系人删除成功（服务器）");
        } else {
            System.out.println("联系人不存在（服务器）");
        }
    }

    private static String viewContact() {
        StringBuilder result = new StringBuilder();
        for (Contact contact : contacts) {
            result.append(contact).append("\n");
        }
        return result.toString();
    }
}